<?php

function check_necessary_extension()
{
    $needed = array('curl', 'zip', 'mbstring');
    $not_loaded = '';
    foreach ($needed as $ext) {
        if (!extension_loaded($ext)) {
            $not_loaded .= $ext . ' ';
        }
    }
    if ($not_loaded) {
        logging\error("缺少以下模块：%s", $not_loaded);
        exit(1);
    }
}

function abort_on_start_warning()
{
    echo "\n\n";
    echo "接下来会删除本目录下除本脚本之外的其它所有数据，请输入 YES 继续: ";
    $line = trim(fgets(STDIN));
    if ($line == "YES") {
        return false;
    } else {
        return true;
    }
}

function rrmdir($path)
{
    logging\info("正在删除目录  %s", $path);
    if (PHP_OS === 'Windows' || PHP_OS === 'WINNT') {
        exec(sprintf("rd /s/q %s", $path));
    } else {
        exec(sprintf("rm -rf %s", $path));
    }
}

function cpdir($from, $to)
{
    logging\info("正在复制目录  %s -> %s", $from, $to);
    if (PHP_OS === 'Windows' || PHP_OS === 'WINNT') {
        exec(sprintf("xcopy %s %s", $from, $to));
    } else {
        exec(sprintf("cp -r %s %s", $from, $to));
    }
}

function rmfile($path)
{
    logging\info("正在删除文件 %s", $path);
    unlink($path);
}

function mkdir_of_file($file)
{
    if (file_exists(dirname($file))) {
        return;
    }
    mkdir(dirname($file), 0777, true);
}

function trimds($s)
{
    return rtrim($s, '/');
}

function join_paths()
{
    return implode('/', array_map('trimds', func_get_args()));
}

function starts_with($haystack, $needle)
{
     $length = strlen($needle);
     return (substr($haystack, 0, $length) === $needle);
}

function ends_with($haystack, $needle)
{
    $length = strlen($needle);
    if ($length == 0) {
        return true;
    }

    return (substr($haystack, -$length) === $needle);
}